<template>
  <Page class="bg-[#f8f9fa] text-[#333] min-h-screen">
    <!-- 头部区域 -->

    <view class="max-w-[750rpx] mx-auto sticky top-0 z-[2]">
      <!-- 头部区域 -->
      <PageHeader title="日结区" :showBack="true" :onlyBack="true"/>
      <view
          class="bg-gradient-to-r from-[#165DFF] to-[#1890ff] sticky top-0 z-[2] text-white px-[32rpx] pt-[100rpx] pb-[20rpx] rounded-b-[32rpx] mb-[-40rpx] relative shadow-md">
        <!-- 返回按钮 -->
        <SearchView/>
      </view>
    </view>

    <!-- 分类区域 -->
    <view
        class="flex overflow-x-auto p-[16rpx_32rpx] mt-[40rpx] bg-white gap-x-[16rpx]"
    >
      <view
          v-for="category in categories"
          :key="category.id"
          class="flex flex-col items-center min-w-[88rpx] p-[12rpx_8rpx] rounded-[16rpx] cursor-pointer transition-all duration-300"
          :class="{
          'bg-[#e6f7ff] font-bold text-[#165DFF] shadow':
            activeTab === category.id,
          'text-[#999]': activeTab !== category.id,
        }"
          @click="
          activeTab = category.id;
          handleCategoryClick(category.name);
        "
      >
        <view
            class="category-icon w-[48rpx] h-[48rpx] rounded-full bg-[#f0f5ff] flex items-center justify-center text-[28rpx] mb-[8rpx] text-[#165DFF]"
        >
          <IconFont :name="category.icon"/>
        </view>
        <view class="category-name text-[22rpx] text-center">{{
            category.name
          }}
        </view>
      </view>
    </view>

    <view
        class="order-list p-[24rpx_32rpx] min-h-[calc(100vh-420rpx)] flex flex-col gap-y-[20rpx]"
    >
      <view
          v-for="(order, index) in filteredOrders"
          :key="index"
          class="order-card bg-white rounded-[24rpx] p-[24rpx] shadow-md relative flex flex-col"
          :class="
          order.status
            ? 'border-l-[8rpx] border-l-[#FF4D4F]'
            : 'border-l-[8rpx] border-l-[#165DFF]'
        "
      >
        <view class="order-header flex justify-between mb-[16rpx] items-center">
          <view class="order-title text-[28rpx] font-bold flex-1 text-[#222]">{{
              order.position_name
            }}
          </view>
          <view
              class="text-[22rpx] px-[20rpx] py-[8rpx] rounded-[16rpx] font-medium bg-gradient-to-r from-[#e3f2fd] to-[#bbdefb] text-[#2196F3]">
            {{ order.status }}
          </view>

        </view>
        <view
            class="order-meta flex mb-[12rpx] flex-wrap gap-x-[16rpx] gap-y-[8rpx]"
        >
          <view class="meta-item flex items-center text-[22rpx] text-[#666]">
            <IconFont name="locationg3" class="mr-[8rpx] text-[#165DFF]"/>
            <text>{{ order.location }}</text>
          </view>
          <!-- <view class="meta-item flex items-center text-[22rpx] text-[#666]">
            <IconFont name="icon-distance" class="mr-[8rpx] text-[#165DFF]" />
            <text>{{ order.distance }}</text>
          </view> -->
          <view class="meta-item flex items-center text-[22rpx] text-[#666]">
            <IconFont name="icon-clock" class="mr-[8rpx] text-[#165DFF]"/>
            <text>{{ order.corporate_name }}</text>
          </view>
        </view>
        <view
            class="order-description text-[22rpx] text-[#666] mb-[16rpx] leading-[1.6]"
        >{{ order.description }}
        </view
        >
        <view class="order-footer flex justify-between items-center mt-[16rpx]">
          <view>
            <view class="order-payment text-[32rpx] font-bold text-[#fa541c]">{{
                order.salary
              }}
            </view>
            <view class="order-time text-[20rpx] text-[#999]">{{
                order.number
              }}
            </view>
          </view>
          <nut-button
              type="primary"
              size="small"
              @click="handleTakeOrder(order.position_name)"
          >
            立即申请
          </nut-button>
        </view>
      </view>
    </view>

  </Page>
</template>

<script setup lang="ts">
import {computed, ref} from "vue";
import Taro from "@tarojs/taro";
import {IconFont} from "@nutui/icons-vue-taro";
import {Input as nutInput, Button as nutButton} from "@nutui/nutui-taro";
import PageHeader from "@/components/PageHeader.vue";
import SearchView from "@/components/SearchView.vue";
import {post} from "@/utils/request";
// 返回上一页
const goBack = () => {
  Taro.navigateBack({
    delta: 1,
  });
};

// 搜索文本
const searchText = ref("");

//定义标签数据获取格式
interface tagsColumn {
  update_time: number,
  create_time: number,
  name: string,
  id: number
}

interface tagsItem {
  columns: tagsColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}

interface QueryParams {
  pageNo?: number;
  pageSize?: number;
  type?: number;
  status?: number
}

interface OrderColumn {
  member_id: null,
  create_time: null,
  time_frame: null,
  pay_number: null,
  position_name: null,
  description: null,
  type: null,
  experience: null,
  salary: null,
  number: null,
  pay_status: null,
  update_time: null,
  name: null,
  corporate_name: null,
  location: null,
  id: null,
  deadline: null,
  status: null
}

interface OrderItem {
  columns: OrderColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}

// 分类数据
const categories = ref([
  /*{name: "餐饮", icon: "icon-restaurant"},
  {name: "促销", icon: "icon-promotion"},
  {name: "搬运", icon: "icon-move"},
  {name: "配送", icon: "icon-delivery"},
  {name: "家政", icon: "icon-housekeeping"},
  {name: "家教", icon: "icon-teacher"},
  {name: "礼仪", icon: "icon-etiquette"},
  {name: "维修", icon: "icon-repair"},*/
]);
const activeCategory = ref(0);

// 优先级筛选
const priorityFilters = ["全部订单", "急招订单"];
const activeFilter = ref(0);
const allOrders = ref([{
  member_id: null,
  create_time: null,
  time_frame: null,
  pay_number: null,
  position_name: null,
  description: null,
  type: null,
  experience: null,
  salary: null,
  number: null,
  pay_status: null,
  update_time: null,
  name: null,
  corporate_name: null,
  location: null,
  id: null,
  deadline: null,
  status: null
}])
// 订单数据
const orders = ref([
  {
    member_id: null,
    create_time: null,
    time_frame: null,
    pay_number: null,
    position_name: null,
    description: null,
    type: null,
    experience: null,
    salary: null,
    number: null,
    pay_status: null,
    update_time: null,
    name: null,
    corporate_name: null,
    location: null,
    id: null,
    deadline: null,
    status: null
  }
  /*{
    title: "餐厅晚班服务员",
    urgent: true,
    badgeText: "急聘",
    location: "青秀区万象城",
    distance: "距离1.5km",
    duration: "4小时/天",
    description:
        "急需3名晚班服务员，工作时间18:00-22:00，主要工作为服务顾客、上菜、清理桌面。有经验者优先。",
    payment: "¥200",
    time: "今日17:30开始",
  },
  {
    title: "超市理货员",
    urgent: false,
    badgeText: "新发布",
    location: "西乡塘区沃尔玛",
    distance: "距离3.2km",
    duration: "8小时/天",
    description:
        "超市早班理货员，工作时间7:00-15:00，要求工作细心，有责任心，能独立完成商品上架理货工作。",
    payment: "¥150",
    time: "每天需1名",
  },
  {
    title: "展会礼仪接待",
    urgent: true,
    badgeText: "急聘",
    location: "国际会展中心",
    distance: "距离4.8km",
    duration: "6小时/天",
    description:
        "急需展会礼仪10名（女性优先），要求162cm以上，形象气质佳，普通话标准，负责展会引导接待。",
    payment: "¥300",
    time: "明日8:30开始",
  },
  {
    title: "物流分拣员",
    urgent: false,
    badgeText: "新发布",
    location: "高新区京东物流园",
    distance: "距离6.5km",
    duration: "5小时/班",
    description:
        "急招晚班分拣员，工作时间20:00-次日1:00，负责快递包裹分类、扫描、装车。",
    payment: "¥180",
    time: "每天需5名",
  },
  {
    title: "家教辅导（初中数学）",
    urgent: false,
    badgeText: "新发布",
    location: "江南区荣宝华商城",
    distance: "距离2.1km",
    duration: "2小时/次",
    description:
        "辅导初一学生数学，每周二、四晚上19:30-21:30，要求有教学经验，有耐心，擅长解题思路讲解。",
    payment: "¥100/次",
    time: "本周开始",
  },*/
]);

// TabBar数据
const userTabs = [
  {icon: "icon-home", label: "接单广场"},
  {icon: "icon-tasks", label: "悬赏大厅"},
  {icon: "icon-education", label: "能力提升"},
  {icon: "icon-factory", label: "工厂招聘"},
  {icon: "icon-user", label: "个人中心"},
];

const workerTabs = [
  {icon: "icon-taskhall", label: "任务大厅"},
  {icon: "icon-wallet", label: "钱包"},
  {icon: "icon-record", label: "接单记录"},
  {icon: "icon-credit", label: "信用评级"},
  {icon: "icon-user", label: "我的"},
];

const merchantTabs = [
  {icon: "icon-data", label: "店铺数据"},
  {icon: "icon-publish", label: "任务发布"},
  {icon: "icon-customers", label: "客户管理"},
  {icon: "icon-orders", label: "订单处理"},
  {icon: "icon-user", label: "我的"},
];

// 活跃状态
const activeRole = ref("user"); // user, worker, merchant
const activeTab = ref(7);
const tagsType = ref([])

// 处理搜索
const handleSearch = () => {
  Taro.showToast({
    title: `搜索: ${searchText.value}`,
    icon: "none",
    duration: 2000,
  });
};


//获取日结招聘标签
getTags()
//TODO：标签没有对应的图片地址参数
function getTags() {
  post('/dictionary/recruitmentDailyLabel').then(res => {
    categories.value = res.data.map((item: tagsItem) => ({
      update_time: item.columns.update_time,
      create_time: item.columns.create_time,
      name: item.columns.name,
      id: item.columns.id
    }))
  })

}
// 处理分类点击
  const handleCategoryClick = (categoryName) => {

    Taro.showToast({
      title: `已筛选: ${categoryName}类订单`,
      icon: "none",
      duration: 2000,
    });
  };

// 处理筛选点击
  const handleFilterClick = computed(( ) => {
    return categories.value.filter(item => item.id === activeCategory.value);
  });

// 处理接单
  const handleTakeOrder = (taskTitle) => {
    const submitForm = {
      recruitmentId: orders.value.find(item => item.position_name === taskTitle)?.id,
      type: 2
    }
    //console.log("报名的ID",submitForm.recruitmentId)
    post('/recruitmentDaily/signUp', submitForm).then(res => {
      Taro.showToast({
        title: `您已申请接单: ${taskTitle}\n等待雇主确认中...`,
        icon: "none",
        duration: 2000,
      });
      if (res.code === 0) {
        Taro.showToast({
          title: `报名成功`,
          icon: "none",
          duration: 2000,
        });
      } else {
        Taro.showToast({
          title: `报名失败`,
          icon: "none",
          duration: 2000,
        });
      }
    })

  };
  const queryParams: QueryParams = {
    pageNo: 1,           // 第1页
    pageSize: 10,        // 每页10条
    //trainingId: 123,     // 示例：主课程ID
    type: 0,              // 示例：筛选类型为2的数据
    status: 0
  };
  post('/recruitmentDaily/all', queryParams).then(res => {
    //console.log("res", res)
    allOrders.value = res.data.map((item: OrderItem) => ({
      member_id: item.columns.member_id,
      create_time: item.columns.create_time,
      time_frame: item.columns.time_frame,
      pay_number: item.columns.pay_number,
      position_name: item.columns.position_name,
      description: item.columns.description,
      type: item.columns.type,
      experience: item.columns.experience,
      salary: item.columns.salary,
      number: item.columns.number,
      pay_status: item.columns.pay_status,
      update_time: item.columns.update_time,
      name: item.columns.name,
      corporate_name: item.columns.corporate_name,
      location: item.columns.location,
      id: item.columns.id,
      deadline: item.columns.deadline,
      status: item.columns.status,

    }));
    //console.log("allOrders",allOrders.value)
  })

// 定义computed属性，根据筛选条件动态过滤
const filteredOrders = computed<OrderColumn[]>(() => {
  return allOrders.value.filter(order => order.type === activeTab.value);
});
//orders.value = filteredOrders.value
//orders.value = allOrders.value
//orders.push(allOrders.value)
//分页
  /*let list = allOrders.value
  if (activeTab.value > 0) {
    orders = orders.filter(c => c.category === categories[activeTab.value])
  }
  filteredCourses.value = list.slice(0, page.value * pageSize)
  noMore.value = filteredCourses.value.length >= list.length*/

// 消息按钮点击
  const handleMessageClick = () => {
    Taro.showToast({
      title: "查看最新任务通知",
      icon: "none",
      duration: 2000,
    });
  };
</script>
